package com.usian.wemedia.service.impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.usian.admin.jwt.AppJwtUtil;
import com.usian.model.base.BaseServiceImpl;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.dtos.WmUserDto;
import com.usian.model.media.pojos.WmUser;
import com.usian.utils.common.AesUtil;
import com.usian.utils.common.BCrypt;
import com.usian.wemedia.mapper.WmUserMapper;
import com.usian.wemedia.service.WmUserService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;

@Service
@PropertySource("classpath:aes.properties")
public class WmUserServiceImpl extends BaseServiceImpl<WmUserMapper, WmUser> implements WmUserService {
    @Value("${key}")
    private String key;
    @Override
    public ResponseResult login(WmUserDto dto) {
        if (dto ==null) return errorParam;
        WmUser one = getOne(Wrappers.<WmUser>lambdaQuery().eq(StringUtils.isNotEmpty(dto.getName()), WmUser::getName, dto.getName()));
        if (one==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"账号不存在");
        }
        String password = dto.getPassword();//md5+aes加密后的密码
        String md5pwd = null;
        try {
            md5pwd = AesUtil.decryptAES(password,key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (BCrypt.checkpw(md5pwd,one.getPassword())){
            HashMap<String,Object> map = new HashMap<>();
            one.setLoginTime(new Date());
            map.put("wmUser",one);
            map.put("token",AppJwtUtil.getToken(Long.valueOf(one.getId())));
            return ResponseResult.okResult(map);
        }else {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }//aes解密后密码
    }
}
